import { defineStore } from 'pinia'
import request from '@/utils/request'
import { ApiRes, ResultData, TopCategory, SubCategory } from '@/types/data'
import { topCategory } from '../constants'
const defaultCategory = topCategory.map(item => {
  return {
    name: item
  }
})

export default defineStore('category', {

  state: () => ({
    list: defaultCategory as ResultData[],
    topCategory: {} as TopCategory,// 二级顶层分类 
    subCategory: {} as SubCategory// 二级分类
  }),

  actions: {
    async getCategoryList() {
      const res = await request.get<ApiRes<ResultData[]>>(
        '/home/category/head'
      )
      // 这里对后台返回回来的数据进行加工，新增一个属性open，标记弹层显示隐藏
      res.data.result.forEach(item => item.open = false)
      this.list = res.data.result
    },
    // 弹层显示隐藏
    show(id: string) {
      const itemObj = this.list.find(item => item.id === id)
      itemObj!.open = true
    },
    hide(id: string) {
      const itemObj = this.list.find(item => item.id === id)
      itemObj!.open = false
    },
    // 顶层类目数据--动态获取--根据id去获取数据
    async getTopCategory(id: string) {
      // axios.get（'/banner'，{params:{id}）
      const res = await request.get<ApiRes<TopCategory>>('/category', {
        params: {
          id,
        },
      })
      this.topCategory = res.data.result
    },
    // 二级分类数据
    async getSubFilter(id: string) {
      const res = await request.get<ApiRes<SubCategory>>('/category/sub/filter', {
        params: {
          id,
        },
      })
      this.subCategory = res.data.result
    }
  },
})